package com.ctrip.ec.biz.dao.user;
import com.ctrip.ec.biz.entity.role.RoleUserEntity;
import com.ctrip.ec.dal.DaoBase;
import com.ctrip.ec.biz.entity.user.UserEntity;
import com.ctrip.ec.dal.DbAccess;
import com.ctrip.ec.dal.EntityBase;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

@Service
public class UserDao extends DaoBase<UserEntity> {
    public UserDao() {
        super(UserEntity.class);
    }
    public UserDao(DbAccess db) {
        super(UserEntity.class,db);
    }

    public UserEntity entityByLoginName(String loginName) throws SQLException {
        String sql = "select * from " + this.getTableName() + " where login_name=?";
        List<UserEntity> list =  this.db.query(UserEntity.class,sql,loginName);
        if(list.size()>0){
            return list.get(0);
        }
        else{
            return null;
        }
    }

    public boolean exist(String loginName, Long id) throws SQLException {
        String sql = "select count(*) from " + this.getTableName() + " where login_name=@0";
        if(id != null){
            sql += " and id != " + id;
        }
        Long count = this.db.getScalar(Long.class, sql, loginName);
        return count >0;
    }

    public List<Long> roleIds(Long userId) throws SQLException {
        String sql = "select role_id from " + EntityBase.getTableName(RoleUserEntity.class) + " where user_id=?";
        List<Long> roleIds = this.db.query(Long.class,sql,userId);
        return roleIds;
    }
}
